package cn.hubujyjs.lp.config;

import cn.hubujyjs.lp.bo.AdminBo;
import cn.hubujyjs.lp.bo.UserBo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.hubujyjs.lp.constant.RedisConst.*;

@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("X-Token");
        if (StrUtil.isBlank(token)){
            return true;
        }
        if (token.startsWith("admin ")){
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(PL_ADMIN_KEY_ + token);
            if (entries.isEmpty()){
                return true;
            }
            AdminBo adminBo = BeanUtil.fillBeanWithMap(entries, new AdminBo(), false);
            AdminHolder.saveUser(adminBo);
            stringRedisTemplate.expire(PL_ADMIN_KEY_+token,LOGIN_USER_TTL, TimeUnit.DAYS);
            return true;
        }else {
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(PL_USER_KEY_ + token);
            if (entries.isEmpty()){
                return true;
            }
            UserBo userDTO = BeanUtil.fillBeanWithMap(entries, new UserBo(), false);
            UserHolder.saveUser(userDTO);
            stringRedisTemplate.expire(PL_USER_KEY_+token,LOGIN_USER_TTL, TimeUnit.DAYS);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
